import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../viewmodels/task_view_model.dart';
import 'add_edit_task_screen.dart';

/// 任务列表tab页
/// 显示所有任务，并提供新增、修改和删除任务的功能
class TaskListTab extends StatefulWidget {
  const TaskListTab({super.key});

  @override
  State<TaskListTab> createState() => _TaskListTabState();
}

class _TaskListTabState extends State<TaskListTab> with SingleTickerProviderStateMixin {
  late TabController _tabController;
  int _currentTabIndex = 0;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
    _tabController.addListener(() {
      setState(() {
        _currentTabIndex = _tabController.index;
      });
      _loadTasks();
    });

    // 初始化时加载任务
    _loadTasks();
  }

  void _loadTasks() {
    final taskViewModel = Provider.of<TaskViewModel>(context, listen: false);
    switch (_currentTabIndex) {
      case 0:
        taskViewModel.loadOngoingTasks();
        break;
      case 1:
        taskViewModel.loadCompletedTasks();
        break;
      case 2:
        taskViewModel.loadNotStartedTasks();
        break;
    }
  }

  void _navigateToAddTask() async {
    await Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => const AddEditTaskScreen()),
    );
    _loadTasks();
  }

  void _navigateToEditTask(String taskId) async {
    await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => AddEditTaskScreen(taskId: taskId),
      ),
    );
    _loadTasks();
  }

  void _deleteTask(String taskId) {
    final taskViewModel = Provider.of<TaskViewModel>(context, listen: false);
    taskViewModel.deleteTask(taskId);
    _loadTasks();
  }

  void _clearCompletedTasks() {
    final taskViewModel = Provider.of<TaskViewModel>(context, listen: false);
    taskViewModel.clearCompletedTasks();
    _loadTasks();
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('任务列表'),
        actions: [
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: _navigateToAddTask,
          ),
          if (_currentTabIndex == 1)
            IconButton(
              icon: const Icon(Icons.delete_sweep),
              onPressed: _clearCompletedTasks,
            ),
        ],
        bottom: TabBar(
          controller: _tabController,
          tabs: const [
            Tab(text: '进行中'),
            Tab(text: '已完成'),
            Tab(text: '未开始'),
          ],
        ),
      ),
      body: Consumer<TaskViewModel>(
        builder: (context, taskViewModel, child) {
          if (taskViewModel.isLoading) {
            return const Center(child: CircularProgressIndicator());
          }

          List<dynamic> tasks;
          switch (_currentTabIndex) {
            case 0:
              tasks = taskViewModel.ongoingTasks;
              break;
            case 1:
              tasks = taskViewModel.completedTasks;
              break;
            case 2:
              tasks = taskViewModel.notStartedTasks;
              break;
            default:
              tasks = [];
          }

          if (tasks.isEmpty) {
            return Center(
              child: Text(_currentTabIndex == 0
                  ? '没有进行中的任务'
                  : _currentTabIndex == 1
                      ? '没有已完成的任务'
                      : '没有未开始的任务'),
            );
          }

          return ListView.builder(
            itemCount: tasks.length,
            itemBuilder: (context, index) {
              final task = tasks[index];
              return ListTile(
                title: Text(task.name),
                subtitle: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('进度: ${task.progress}'),
                    Text('${task.startDate.toString().split(' ')[0]} - ${task.endDate.toString().split(' ')[0]}'),
                    if (task.notes.isNotEmpty) Text('备注: ${task.notes}'),
                  ],
                ),
                trailing: Row(
                  mainAxisSize: MainAxisSize.min,
                  children:
                  [
                    if (_currentTabIndex == 0 || _currentTabIndex == 2)
                      IconButton(
                        icon: const Icon(Icons.edit),
                        onPressed: () => _navigateToEditTask(task.id),
                      ),
                    if (_currentTabIndex == 1)
                      IconButton(
                        icon: const Icon(Icons.delete),
                        onPressed: () => _deleteTask(task.id),
                      ),
                  ],
                ),
              );
            },
          );
        },
      ),
    );
  }
}